﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/SubMesh/Split/UV Islands",
            "Split a mesh into meshes by uv-islands. " +
            "Works on a mesh with one sub-mesh. " +
            "The source is disabled and new renderers are created." +
            " (Slow)",
            ContextRequirements.SingleSubMesh, 0)]
        public static void RendererUVExplode()
        {
            RendererUVExplode(false);
        }

        [CtxMenuItem("Renderer/SubMesh/Split/UV Islands Compare Vertices",
           "Split a mesh into meshes by uv-islands and vertex  positions" +
           "Works on a mesh with one sub-mesh. " +
           "The source is disabled and new renderers are created." +
            " (Slow)",
           ContextRequirements.SingleSubMesh, 0)]
        public static void RendererUVExplode2()
        {
            RendererUVExplode(true);
        }

        public static void RendererUVExplode(bool compareVertices)
        {
            var selected = new List<Object>();
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasSharedMesh(context)) continue;
                if (!SkinnContext.IsVertexCountOkay(context, "generation may take awhile.", 3500)) continue;

                var sharedMesh = context.GetSharedMesh();
                var meshes = SkinnEx.GetMeshIslands(sharedMesh, compareVertices);
                var root = new GameObject(context.name);
                root.transform.SetParent(context.transform.parent);
                Undo.RegisterCreatedObjectUndo(root, "Split Islands");

                for (int i = 0; i < meshes.Length; i++)
                {
                    if (!meshes[i]) continue;
                    var renderer = context.Clone(true) as Renderer;
                    renderer.SetSharedMesh(meshes[i]);
                    renderer.transform.SetParent(root.transform);
                    renderer.name += string.Format("_UVIsland_{0}", i);
                    Undo.RegisterCreatedObjectUndo(renderer.gameObject, "Split Islands");
                    selected.Add(renderer.gameObject);
                }

                SkinnContext.UndoRecord(context, "Split Islands");
                context.gameObject.SetActive(false);
            }

            if (selected.Count > 0) Selection.objects = selected.ToArray();
            SkinnContext.Finished();
        }
    }
}